package com.railwayservice.user.web;

import com.railwayservice.application.config.AppConfig;
import com.railwayservice.application.util.ExcelExportUtil;
import com.railwayservice.application.vo.PageData;
import com.railwayservice.application.vo.PageParam;
import com.railwayservice.application.vo.ResultMessage;
import com.railwayservice.user.entity.User;
import com.railwayservice.user.service.UserService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 用户模块请求控制器。
 *
 * @author lid
 * @date 2017.2.4
 */
@Controller
@RequestMapping(value = "/user", method = {RequestMethod.GET, RequestMethod.POST})
@Api(value = "用户模块请求控制器", description = "用户模块的相关操作")
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 新增用户信息
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage addUser(User user) {
        logger.info("用户控制层->添加用户->用户名:" + user.getName());

        userService.addUser(user);
        return ResultMessage.newSuccess("新增用户成功！");

    }

    /**
     * 更新用户信息。
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage updateUser(User user) {
        logger.info("用户控制层->更新用户->用户名:" + user.getName());

        userService.updateUser(user);
        return ResultMessage.newSuccess("修改用户成功！");

    }

    /**
     * 查询所有用户。
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
//    @Authorize( type = AppConfig.AUTHORITY_ADMIN,value={"WEB_USER_WXUSER_LIST"})
    public ResultMessage getAllUser() {
        logger.info("用户控制层->查询所有用户");

        List<User> list = userService.getAllUser();
        System.out.println("list.size():" + list.size());
        return ResultMessage.newSuccess("获取用户成功！");

    }

    /**
     * 根据id查询单个用户详细信息
     */
    @ResponseBody
    @RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST})
//    @Authorize( type = AppConfig.AUTHORITY_ADMIN,value={"WEB_USER_WXUSER_LIST"})
    public ResultMessage getUserById(String id) {
        logger.info("用户控制层->详细用户信息->用户ID:" + id);

        User user = userService.getUserByUserId(id);
        if (null == user) {
            return ResultMessage.newFailure("未找到相关用户记录！");
        }
        return ResultMessage.newSuccess("获取用户信息成功！").setData(user);

    }

    /**
     * 根据openid查询单个用户信息
     */
    @ResponseBody
    @RequestMapping(value = "/getByOpenid", method = {RequestMethod.GET, RequestMethod.POST})
//    @Authorize( type = AppConfig.AUTHORITY_ADMIN,value={"WEB_USER_WXUSER_LIST"})
    public ResultMessage getUserByOpenid(String openid) {
        logger.info("用户控制层->单个用户信息->openID:" + openid);

        User user = userService.getUserByOpenid(openid);
        if (null == user) {
            return ResultMessage.newFailure("未找到相关用户记录！");
        }
        return ResultMessage.newSuccess("获取用户信息成功！").setData(user);

    }

    /**
     * 查询所有用户(分页)
     */
    @ResponseBody
    @RequestMapping(value = "/queryAllUser", method = {RequestMethod.GET, RequestMethod.POST})
//    @Authorize( type = AppConfig.AUTHORITY_ADMIN,value={"WEB_USER_WXUSER_LIST"})
    public ResultMessage queryAllUser(PageParam param, String nickName, String phoneNo) {
        logger.info("用户控制层->查询所有用户->用户昵称:" + nickName + ", 联系方式：" + phoneNo);

        Page<User> userPage = userService.queryAllUser(nickName, phoneNo, param.newPageable());
        return ResultMessage.newSuccess("获取用户列表成功！").setData(new PageData(userPage));

    }

    /**
     * 查询所有推广用户(分页)
     */
    @ResponseBody
    @RequestMapping(value = "/queryPromotion", method = {RequestMethod.GET, RequestMethod.POST})
//    @Authorize( type = AppConfig.AUTHORITY_ADMIN,value={"WEB_USER_WXUSER_LIST"})
    public ResultMessage queryPromotion(PageParam param, String nickName) {
        logger.info("用户控制层->查询所有用户推广人数->参数:" + nickName);

        Page<User> dataPage = userService.queryPromotion(nickName, param.newPageable());
        return ResultMessage.newSuccess("查询所有用户推广人数成功！").setData(new PageData(dataPage));

    }

    /**
     * 导出商务财务
     *
     * @return ResultMessage
     * @author xuy
     * @date 2017.2.8
     */
    @ResponseBody
    @RequestMapping(value = "/downPromotion", method = {RequestMethod.GET, RequestMethod.POST})
    public void downPromotion(String nickName, HttpServletRequest request, HttpServletResponse resp) {
        logger.info("用户控制层->查询所有用户推广人数->参数:" + nickName);
        try {
            request.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/x-download");
            resp.addHeader("Content-Disposition", "attachment;filename=" + "download.xls");
            List<User> result = userService.queryPromotion(nickName);

            ExcelExportUtil<User> util = new ExcelExportUtil<User>();
            String[] title = {"微信昵称", "微信ID", "性别", "手机号", "省", "市", "关注时间", "总推荐人数"};
            String[] values = {"nickName", "openid", "genderStr", "phoneNo", "province", "city", "createDate", "inviteCount"};
            int[] widths = {120, 120, 120, 120, 120, 120, 120, 120};
            util.exportExcel(title, values, widths, result, resp.getOutputStream());
            resp.getOutputStream().close();
        } catch (Exception e) {
            logger.error("导出用户推荐人数数据异常：", e);
        }
    }

    /**
     * 查询用户推广页面的信息：推广总数、最近推广的5个人、推广链接
     */
    @ResponseBody
    @RequestMapping(value = "/inviteInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage inviteInfo(HttpServletRequest request, HttpServletResponse resp) {
        User user = (User) request.getSession().getAttribute(AppConfig.USER_SESSION_KEY);
        logger.info("查询用户推广页面的信息->openid:" + user.getOpenid()+",nickname:"+user.getNickName());
        Map<String, Object> map = userService.getInviteInfo(user.getOpenid());
        return ResultMessage.newSuccess("查询用户邀请信息成功！").setData(map);
    }
}
